package com.github.byakkili.bim.protocol.json.ws;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

/**
 * @author Guannian Li
 */
@Slf4j
public class WsClient extends WebSocketClient implements AutoCloseable {

    private final BlockingQueue<String> queue = new SynchronousQueue<>();

    public WsClient(String url) throws URISyntaxException {
        super(new URI(url), new Draft_6455());
    }

    @Override
    public void send(String text) {
        log.info("WsClient send info: {}", text);
        super.send(text);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("WsClient open.");
    }

    @Override
    public void onMessage(String jsonStr) {
        log.info("WsClient receive: {}", jsonStr);
        queue.offer(jsonStr);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("WsClient close.");
    }

    @Override
    public void onError(Exception e) {
        log.error("WsClient error.", e);
    }

    public String getReceiveMsg() throws InterruptedException {
        return queue.take();
    }
}